package com.xzx.redislock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xzx.redislock.entity.RedisLock;
import com.xzx.redislock.mapper.RedisLockMapper;
import com.xzx.redislock.service.IMiaoShaService;
import com.xzx.redislock.util.RedisLockUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class MiaoShaSerivcieImpl implements IMiaoShaService {

    @Resource
    private RedisLockMapper redisLockMapper;
    @Autowired
    private RedisLockUtil redisLockUtil;
    private final int TIME_OUT = 5*1000;

    /**
     * redis锁测试秒杀
     * @return
     */
    @Override
    public String miaoSha(String code,Integer countNum) {
        //上锁
        Long time = System.currentTimeMillis()+ TIME_OUT;
        if (!redisLockUtil.onLock(code,String.valueOf(time))){
            //获取锁失败,直接快速失败,避免线程等待
            return "排队人数太多，请稍后再试";
        }
        System.out.println("获取的时间戳====>"+time);
        try {
            //获得锁
            QueryWrapper<RedisLock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code",code);
            RedisLock redisLock = redisLockMapper.selectOne(queryWrapper);
            if (Objects.nonNull(redisLock)){
                if (Integer.valueOf(redisLock.getStore()) <= 0){
                    return "对不起,商品卖完了,"+redisLock.getStore();
                }
                if (Integer.valueOf(redisLock.getStore()) < countNum){
                    return "库存不足,剩余商品,"+redisLock.getStore();
                }
                System.out.println("剩余库存："+redisLock.getStore());
                System.out.println("扣除库存："+countNum);
                redisLock.setStore(String.valueOf(Integer.valueOf(redisLock.getStore())-countNum));
                redisLockMapper.updateById(redisLock);
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return "恭喜您，购买成功！";
            }else {
                return "获取库存失败。";
            }
        }finally {
            redisLockUtil.releaseLock(code,String.valueOf(time));
            System.out.println("释放锁的时间戳："+time);
        }
    }
}
